<template>
  <div class="login-container">
    <div class="login-wrapper">
      <!-- 顶部Logo区域 -->
      <div class="login-header">
        <div class="logo-section">
          <div class="logo-icon">
            <svg width="60" height="60" viewBox="0 0 60 60" fill="none">
              <rect width="60" height="60" rx="16" fill="#007AFF"/>
              <path d="M20 30L28 38L40 22" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
          <h1 class="app-title">AutoRun</h1>
        </div>
      </div>

      <!-- 登录表单卡片 -->
      <div class="login-card">
        <el-form 
          ref="formRef" 
          :model="form" 
          :rules="rules" 
          class="login-form"
          size="large"
          @submit.prevent="handleSubmit"
        >
          <el-form-item prop="username" class="form-item">
            <label class="field-label">用户名</label>
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              clearable
              class="apple-input"
              autocomplete="username"
              @keyup.enter="handleSubmit"
            />
          </el-form-item>
          
          <el-form-item prop="password" class="form-item">
            <label class="field-label">密码</label>
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              show-password
              clearable
              class="apple-input"
              autocomplete="new-password"
              @keyup.enter="handleSubmit"
            />
          </el-form-item>
          
          <div class="submit-section">
            <el-button 
              type="primary" 
              class="submit-btn"
              :loading="loading"
              @click.prevent="handleSubmit"
            >
              登录
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '../api/auth'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const formRef = ref()
    const loading = ref(false)
    
    const form = reactive({
      username: '',
      password: ''
    })
    
    const rules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 50, message: '用户名长度在3到50个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    })
    
    const handleSubmit = async (event) => {
      // 阻止表单默认提交行为
      if (event) {
        event.preventDefault()
        event.stopPropagation()
      }
      
      try {
        // 表单验证
        const valid = await formRef.value.validate()
        if (!valid) {
          return false
        }
        
        loading.value = true
        
        // 登录逻辑
        const response = await login(form.username, form.password)
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        ElMessage.success('登录成功！正在跳转...')
        
        // 延迟跳转，让用户看到成功消息
        setTimeout(() => {
          router.push('/dashboard')
        }, 1000)
      } catch (error) {
        console.error('登录失败:', error)
        
        // 更详细的错误处理
        let errorMessage = '登录失败，请重试'
        
        if (error.response) {
          // 服务器返回的错误
          const status = error.response.status
          const data = error.response.data
          
          if (status === 401) {
            errorMessage = '用户名或密码错误'
          } else if (status === 400) {
            errorMessage = data?.message || '请求格式错误'
          } else if (status === 500) {
            errorMessage = '服务器内部错误，请稍后重试'
          } else if (data?.message) {
            errorMessage = data.message
          }
        } else if (error.code === 'ECONNABORTED') {
          errorMessage = '请求超时，请检查网络连接'
        } else if (error.code === 'ERR_NETWORK') {
          errorMessage = '网络错误，请检查后端服务是否启动'
        } else if (error.message) {
          errorMessage = error.message
        }
        
        ElMessage.error(errorMessage)
      } finally {
        loading.value = false
      }
    }
    
    return {
      formRef,
      loading,
      form,
      rules,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background-color: #f5f5f7;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-wrapper {
  width: 100%;
  max-width: 400px;
  display: flex;
  flex-direction: column;
  gap: 32px;
}

/* 顶部Logo区域 */
.login-header {
  text-align: center;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.logo-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.app-title {
  font-size: 32px;
  font-weight: 700;
  color: #1d1d1f;
  letter-spacing: -0.05em;
  margin: 0;
}

/* 登录卡片 */
.login-card {
  background: #ffffff;
  border-radius: 20px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.04);
}

/* 表单样式 */
.login-form {
  width: 100%;
}

.form-item {
  margin-bottom: 24px;
}

.field-label {
  display: block;
  font-size: 15px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 8px;
  letter-spacing: -0.024em;
}

.apple-input :deep(.el-input__wrapper) {
  height: 52px;
  border-radius: 12px;
  border: 1px solid #d2d2d7;
  background-color: #ffffff;
  font-size: 17px;
  padding: 0 16px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: none;
}

.apple-input :deep(.el-input__wrapper:hover) {
  border-color: #007aff;
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
}

.apple-input :deep(.el-input__wrapper.is-focus) {
  border-color: #007aff;
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.15);
}

.apple-input :deep(.el-input__inner) {
  color: #1d1d1f;
  font-weight: 400;
  letter-spacing: -0.022em;
  height: 100%;
}

.apple-input :deep(.el-input__inner::placeholder) {
  color: #86868b;
  font-weight: 400;
}

/* 提交按钮 */
.submit-section {
  margin: 32px 0 24px 0;
}

.submit-btn {
  width: 100%;
  height: 52px;
  background-color: #007aff;
  border: none;
  border-radius: 12px;
  font-size: 17px;
  font-weight: 600;
  color: #ffffff;
  letter-spacing: -0.022em;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
}

.submit-btn:hover {
  background-color: #0051d5;
  transform: translateY(-1px);
  box-shadow: 0 8px 25px rgba(0, 122, 255, 0.3);
}

.submit-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: 16px;
  }
  
  .login-card {
    padding: 24px;
    border-radius: 16px;
  }
  
  .app-title {
    font-size: 28px;
  }
}

/* 隐藏Element Plus的默认样式 */
:deep(.el-form-item__label) {
  display: none;
}

:deep(.el-form-item__error) {
  font-size: 13px;
  color: #ff3b30;
  font-weight: 400;
  letter-spacing: -0.024em;
  margin-top: 4px;
}

/* 消息提示样式优化 */
:deep(.el-message) {
  border-radius: 12px !important;
  font-weight: 500 !important;
  letter-spacing: -0.022em !important;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15) !important;
}

:deep(.el-message--success) {
  background-color: #34c759 !important;
  border-color: #34c759 !important;
}

:deep(.el-message--error) {
  background-color: #ff3b30 !important;
  border-color: #ff3b30 !important;
}
</style> 